/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.utils.fastjson2;

import com.alibaba.fastjson2.filter.ValueFilter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @packageName com.ktjiaoyu.utils.fastjson2
 * @fileName FastJson2DateValueFilter.java
 * @createTime 2024/10/20 15:04
 * @lastModify 2024/10/20 15:04
 */
public class FastJson2DateValueFilter implements ValueFilter {

    public FastJson2DateValueFilter(LinkedHashMap<String, String> dateMappings) {
        this.dateMappings = dateMappings;
    }
    // 定义格式如下
    // {
    //   "(?i)^.*(day|date)$" : "yyyy-MM-dd",
    //   "(?i)^.*(time)$" : "yyyy-MM-dd HH:mm:ss",
    //   "(?i)^.*(datetime)$" : "HH:mm:ss"
    // }
    private LinkedHashMap<String, String> dateMappings = null;

    @Override
    public Object apply(Object object, String propertyName, Object value) {
        if(dateMappings == null){
            return value;
        }
        // 要判断数据类型
        if(value instanceof Date){
            Set<String> keySet = dateMappings.keySet();
            for (String pattern : keySet) {
                // 循环所有的正则表达式，判断属性名是否符合正则要求
                if(propertyName.matches(pattern)){
                    // 符合要求的取出格式进行转换
                    String dateFormat = dateMappings.get(pattern);
                    // 返回对应格式
                    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
                    return formatter.format((Date)value);
                }
            }
        }
        return value;
    }
}
